package com.bw.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bw.config.Result;
import com.bw.domain.SysDictData;
import com.bw.service.SysDictDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import java.util.*;

/**
 * @author 王钰--WY
 * @create 2023-08-15 14:34
 */
@RestController
@RequestMapping("/dict/data")
public class SysDictDataController {
    @Autowired
    SysDictDataService sysDictDataService;
    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 项目启动时 sys_normal_disable类型数据存入redis
     */
    @PostConstruct
    public void initCache(){
        System.out.println("从MySql获取存入redis");
        List<SysDictData> list = sysDictDataService.list(
                new LambdaQueryWrapper<SysDictData>()
                        .eq(SysDictData::getDictType, "sys_normal_disable")
        );
        redisTemplate.opsForList().rightPushAll("DICT_DATA_sys_normal_disable",list);
    }

    /**
     * OpenFeign远程调用获取字典数据
     * @param dictType
     * @return
     */
    @GetMapping("/getDataByType")
    public Map<String, List<SysDictData>> getDataByType(String dictType){
        List<SysDictData> list=null;
        if (redisTemplate.hasKey("DICT_DATA_"+dictType)){
            System.out.println("从redis获取");
            list= redisTemplate.opsForList().range("DICT_DATA_" + dictType, 0, -1);
        }else {
            System.out.println("从MySql获取");
            list = sysDictDataService.list(
                    new LambdaQueryWrapper<SysDictData>()
                            .eq(SysDictData::getDictType, dictType)
            );
            redisTemplate.opsForList().rightPushAll("DICT_DATA_" + dictType,list);
        }
        Map<String,List<SysDictData>> map=new HashMap<>();
        map.put("data",list);
        return map;
    }
    @PostMapping("/list")
    public Result<List<SysDictData>> getDataByType(Page page, @RequestBody SysDictData sysDictData){
        List<SysDictData> list=null;
        if (ObjectUtil.isNotEmpty(sysDictData.getDictLabel())||ObjectUtil.isNotEmpty(sysDictData.getStatus())){
            System.out.println("有查询条件从MySql获取");
            list = sysDictDataService.page(page
                    , new LambdaQueryWrapper<SysDictData>()
                            .eq(SysDictData::getDictType, sysDictData.getDictType())
                            .like(ObjectUtil.isNotEmpty(sysDictData.getDictLabel()), SysDictData::getDictLabel, sysDictData.getDictLabel())
                            .eq(ObjectUtil.isNotEmpty(sysDictData.getStatus()), SysDictData::getStatus, sysDictData.getStatus())
            ).getRecords();
            return Result.ok(list);
        }
        //没有查询条件
        if (redisTemplate.hasKey("DICT_DATA_"+sysDictData.getDictType())){
            System.out.println("从redis获取");
            list= redisTemplate.opsForList().range("DICT_DATA_" + sysDictData.getDictType(), (page.getCurrent()-1)*page.getSize(), page.getCurrent()*page.getSize());
            return Result.ok(list);
        }
        System.out.println("从MySql获取");
        list = sysDictDataService.page(page
                , new LambdaQueryWrapper<SysDictData>()
                        .eq(SysDictData::getDictType, sysDictData.getDictType())
        ).getRecords();
        redisTemplate.opsForList().rightPushAll("DICT_DATA_" + sysDictData.getDictType(),list);
        return Result.ok(list);
    }
    @PostMapping("/saveDictData")
    public Boolean saveDictData(@RequestBody SysDictData sysDictData) throws InterruptedException {
        redisTemplate.delete("DICT_DATA_" + sysDictData.getDictType());
        sysDictData.setCreateBy("暂未设置");
        sysDictData.setCreateTime(new Date());
        boolean b = sysDictDataService.save(sysDictData);
        Thread.sleep(500);
        redisTemplate.delete("DICT_DATA_" + sysDictData.getDictType());
        return b;
    }
    @PostMapping("/updateDictData")
    public Boolean updateDictData(@RequestBody SysDictData sysDictData) throws InterruptedException {
        redisTemplate.delete("DICT_DATA_" + sysDictData.getDictType());
        sysDictData.setUpdateBy("暂未设置");
        sysDictData.setUpdateTime(new Date());
        boolean b = sysDictDataService.updateById(sysDictData);
        Thread.sleep(500);
        redisTemplate.delete("DICT_DATA_" + sysDictData.getDictType());
        return b;
    }
    @GetMapping("/delById/{dictCode}")
    public Boolean delById(@PathVariable("dictCode") Integer dictCode) throws InterruptedException {
        SysDictData dictData = sysDictDataService.getById(dictCode);
        redisTemplate.delete("DICT_DATA_" + dictData.getDictType());
        boolean b = sysDictDataService.removeById(dictCode);
        Thread.sleep(500);
        redisTemplate.delete("DICT_DATA_" + dictData.getDictType());
        return b;
    }
    @GetMapping("/delByIds/{ids}")
    public Boolean delByIds(@PathVariable("ids")String ids) throws InterruptedException {
        List<String> list = Arrays.asList(ids.split(","));
        SysDictData dictData = sysDictDataService.getById(list.get(0));
        redisTemplate.delete("DICT_DATA_" + dictData.getDictType());
        boolean b = sysDictDataService.removeByIds(list);
        Thread.sleep(500);
        redisTemplate.delete("DICT_DATA_" + dictData.getDictType());
        return b;
    }
    @GetMapping("/getById/{dictCode}")
    public SysDictData getById(@PathVariable("dictCode")Integer dictCode){
        SysDictData dictData = sysDictDataService.getById(dictCode);
        return dictData;
    }
}
